package net.crashtoot.picasa.core.dao.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.crashtoot.picasa.core.dao.PhotoDao;
import net.crashtoot.picasa.core.model.Account;
import net.crashtoot.picasa.core.model.Album;
import net.crashtoot.picasa.core.model.Photo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

@Repository("albumDao")
public class PhotoDaoPicasa implements PhotoDao {
    private static final Log log = LogFactory.getLog(PhotoDaoPicasa.class);

    private static final String API_PREFIX = "http://picasaweb.google.com/data/feed/api/user/";

    /**
     * Ouverture au service picasa et connection du compte.
     */
    private PicasawebService getService(final Account account) {
        try {
            log.info("connecting...");
            final PicasawebService service = new PicasawebService("CrashTootPicasaClient");
            service.setUserCredentials(account.getEmail(), account.getPassword());
            log.info(account.getEmail() + " connected");

            return service;

        } catch (final AuthenticationException e) {
            throw new IllegalArgumentException("Illegal username/password combination.");
        }
    }

    public List<Album> getAlbums(final Account account) throws IOException, ServiceException {

        final String albumUrl = API_PREFIX + account.getUsername() + "?kind=album";
        log.info("albumUrl=" + albumUrl);
        final UserFeed userFeed = getService(account).getFeed(new URL(albumUrl), UserFeed.class);

        final List<Album> albums = new ArrayList<Album>();

        for (final AlbumEntry album : userFeed.getAlbumEntries()) {
            albums.add(new Album(album));
        }

        return albums;
    }

    @Override
    public List<Photo> getPhotos(final String album, final Account account) throws IOException, ServiceException {

        final URL albumAndPhotosUrl = new URL(API_PREFIX + account.getUsername() + "/album/" + album + "?kind=photo");

        // Send the request for the album's photos.
        final AlbumFeed albumFeed = getService(account).getFeed(albumAndPhotosUrl, AlbumFeed.class);

        final List<Photo> albums = new ArrayList<Photo>();

        for (final PhotoEntry photo : albumFeed.getPhotoEntries()) {
            albums.add(new Photo(photo));
        }

        return albums;
    }
}
